﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading;
namespace MyWindowsService
{
    /// <summary>
    /// 我的Windows服务
    /// </summary>
    public class MyFileSystemWatcherService : ServiceBase
    {
        /// <summary>
        /// 初始化对象
        /// </summary>
        public MyFileSystemWatcherService()
        {
            this.ServiceName = "MyFileSystemWatcher";
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            this.StartFileSystemWatching();
        }

        /// <summary>
        /// 终止服务
        /// </summary>
        protected override void OnStop()
        {
            if (myWatchers != null)
            {
                foreach (System.IO.FileSystemWatcher w in myWatchers)
                {
                    w.EnableRaisingEvents = false;
                    w.Dispose();
                }
                myWatchers = null;
            }
            Util.CloseDBConnection();
            base.OnStop();
        }

        /// <summary>
        /// 暂停服务
        /// </summary>
        protected override void OnPause()
        {
            if (myWatchers != null)
            {
                foreach (System.IO.FileSystemWatcher w in myWatchers)
                {
                    w.EnableRaisingEvents = false;
                }
            }
            base.OnPause();
        }

        /// <summary>
        /// 重新运行暂停的服务
        /// </summary>
        protected override void OnContinue()
        {
            if (myWatchers != null)
            {
                foreach (System.IO.FileSystemWatcher w in myWatchers)
                {
                    w.EnableRaisingEvents = true;
                }
            }
            base.OnContinue();
        }

        /// <summary>
        /// 文件系统监视器列表
        /// </summary>
        private System.Collections.ArrayList myWatchers = null;

        /// <summary>
        /// 开始启动文件系统监视
        /// </summary>
        /// <returns>操作是否成功</returns>
        internal bool StartFileSystemWatching()
        {
            myWatchers = new System.Collections.ArrayList();
            MyConfig.Instance.Load();
            string[] paths = MyConfig.Instance.WatchedPaths;
            System.Text.StringBuilder myPathList = new StringBuilder();
            if (paths != null)
            {
                foreach (string path in paths)
                {
                    if (System.IO.Path.IsPathRooted(path) == false)
                    {
                        continue;
                    }
                    string BasePath = null;
                    string Filter = null;

                    if (System.IO.Directory.Exists(path))
                    {
                        BasePath = path;
                        Filter = "*.*";
                    }
                    else
                    {
                        BasePath = System.IO.Path.GetDirectoryName(path);
                        Filter = System.IO.Path.GetFileName(path);
                    }
                    if (BasePath == null)
                    {
                        continue;
                    }
                    BasePath = BasePath.Trim();
                    if (BasePath.ToUpper().StartsWith(System.Windows.Forms.Application.StartupPath))
                    {
                        // 不能监视程序本身所在的目录的文件系统更改
                        continue;
                    }

                    if (System.IO.Directory.Exists(BasePath) == false)
                    {
                        // 不能监视不存在的目录
                        continue;
                    }
                    if (myPathList.Length > 0)
                    {
                        myPathList.Append(";");
                    }
                    myPathList.Append(path);
                    System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher();
                    watcher.Path = BasePath;
                    watcher.Filter = Filter;
                    watcher.EnableRaisingEvents = true;
                    watcher.IncludeSubdirectories = false;
                    if (MyConfig.Instance.LogChanged)
                    {
                        watcher.Changed += delegate(object sender, System.IO.FileSystemEventArgs args)
                            {
                                WriteFileSystemLog(args.FullPath, args.ChangeType.ToString());
                            };
                    }
                    if (MyConfig.Instance.LogCreated)
                    {
                        watcher.Created += delegate(object sender, System.IO.FileSystemEventArgs args)
                            {
                                WriteFileSystemLog(args.FullPath, args.ChangeType.ToString());
                            };
                    }
                    if (MyConfig.Instance.LogDeleted)
                    {
                        watcher.Deleted += delegate(object sender, System.IO.FileSystemEventArgs args)
                            {
                                WriteFileSystemLog(args.FullPath, args.ChangeType.ToString());
                            };
                    }
                    if (MyConfig.Instance.LogRenamed)
                    {
                        watcher.Renamed += delegate(object sender, System.IO.RenamedEventArgs args)
                            {
                                WriteFileSystemLog(args.FullPath, args.ChangeType.ToString());
                            };
                    }
                    myWatchers.Add(watcher);
                }//foreach
                this.EventLog.WriteEntry(
                    "开始监视文件系统 " + myPathList.ToString(),
                    EventLogEntryType.Information);
            }//if
            return true;
        }

        private void WriteFileSystemLog(string ObjectName, string EventStyle)
        {
            System.Data.IDbConnection conn = Util.DBConnection;
            if (conn == null)
                return;
            // 将监视结果添加到数据库中
            using (System.Data.IDbCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = "Insert Into FileSystemLog ( RecordID , WatchTime , ObjectName , EventStyle ) Values ( '" + System.Guid.NewGuid().ToString() + "' , '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' , ? , '" + EventStyle + "')";
                System.Data.IDbDataParameter p = cmd.CreateParameter();
                p.Value = ObjectName;
                cmd.Parameters.Add(p);
                cmd.ExecuteNonQuery();
            }
        }
    }//public class MyService : ServiceBase
}